package com.lyl.security.common.config;

import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Mr.Luo
 * @date 2022-09-09 15:30
 * @desc 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> onException(Exception e) {
        log.error("系统异常", e);
        return Result.build(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Object> onAuthenticationException(AuthenticationException e) {
        log.error("认证异常", e);
        return Result.build(ErrorCode.UNAUTHORIZED).setMsg(e.getMessage());
    }

}
